package com.cx.mall.factory.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class RtGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求request
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应response
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求的Uri
        String uri = request.getURI().toString();
        // 获取讲求的时间
        long startTime = System.currentTimeMillis();
        log.info("请求开始：{}，开始时间：{}", uri, startTime);
        /*
         * 放行请求和响应，并记录请求的响应时间，
         * 注意
         * （1）响应式编程与mvc的过滤器不同，mvc的过滤器是同步的，而响应式编程是异步的
         * （2）响应式编程的响应，需要返回一个Mono对象
         * （3）响应式编程的doFinally()方法，会在响应结束前执行
         * （4）响应式编程的then()方法，会在响应成功时执行
         */
        Mono<Void> filter = chain.filter(exchange)
                .doFinally(res -> {
                    long endTime = System.currentTimeMillis();
                    log.info("请求结束：{}，结束时间：{}", uri, endTime);
                    log.info("请求耗时：{}", endTime - startTime);
                });
        return filter;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
